<template>
  <div>
    <el-divider /><!--下划线-->
    <div class="userinfo">
      <el-avatar :size="30" :src="circleUrl"></el-avatar>
      <span class="username">{{ comment.username }}</span>
      <span class="time">{{ createdAt }}</span>
    </div>

    <p>{{ comment.content }}</p>

    <div v-if="isMy">
      <el-button link @click="showEditModal =true">编辑</el-button>
      <el-button link style="color: red;" @click="del">删除</el-button>
    </div>

    <!-- 编辑留言 -->
    <el-dialog title="编辑留言" v-model="showEditModal" width="50%">
      <el-input type="textarea" :rows="3" v-model="newContent"></el-input>
      <span slot="footer" class="dialog-footer">
                <el-button @click="showEditModal = false">取 消</el-button>
                <el-button type="primary" @click="update">确 定</el-button>
            </span>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { delCommentService, updateCommentService } from '@/services/comment'
import { formatDate } from '@/utils/dt'
import { computed, onMounted, ref, inject } from 'vue'

const useProvidedUpdateCommentList = inject('UpdateCommentList')//注入父辈提供的方法
const useCurrentUserName = inject('currentUserName')//注入当前用户名
onMounted(() => newContent.value = props.comment['content'])

const props = defineProps(['comment'])

const circleUrl = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')
const showEditModal = ref(false)
const newContent = ref('')

const createdAt = computed(() => formatDate(props.comment['createdAt']))//格式化日期

const isMy = computed(() => {
  // 判断该留言是不是自己的
  const curData = props.comment
  if (!curData) return false
  return curData['username'] === useCurrentUserName.value
})



async function update() {
  showEditModal.value = false //关闭弹框
  // 更新数据
  const res = await updateCommentService(props.comment['_id'], newContent.value) //更新db
  console.log('fe update res =\n',res)
  if (!res.ok)
    alert('更新留言失败')
  await useProvidedUpdateCommentList(res.data) //更新留言列表
  alert('修改成功')
}

async function del() {
  if (window.confirm('确定删除？')) {
    let res = await delCommentService(props.comment['_id'])
    if (res && res['ok'])
      location.reload()//重新加载页面
    else
      alert('del error')
  }
}

</script>

<style lang="stylus" scoped>
.userinfo
  position: relative

.username
  position: absolute;
  margin-left: 5px;
  margin-top: 7px;

.time
  font-size: 12px;
  color: #666;
  position: absolute;
  right: 0;

</style>
